let app = getApp();

let mappingAdress = new Map([
  ["/feedback/weChat/insertFeedback", "/S62070000"]
, ["/file/queryByBusinessIds", "/Q62070000"]
, ["/weChat/userMessage/queryMyMessage", "/S62070001"]
, ["/weChat/userMessage/updateReadFlag", "/S62070002"]
, ["/weChat/userMessage/batchUpdateReadFlag", "/S62070003"]
, ["/weChat/userMessage/queryMyMessageSum", "/Q62070001"]
, ["/weChat/userMessage/queryWhetherUserReceiveFlag", "/Q62070002"]
, ["/weChat/userMessage/UpdateUserReceiveFlag", "/S62070004"]
, ["/weChat/production/queryAllTypeAndNameList", "/Q62070003"]
, ["/weChat/production/queryByCondition", "/Q62070004"]
, ["/weChat/solution/querySolutionList", "/Q62070005"]
, ["/weChat/solution/querySolution", "/Q62070006"]
, ["/weChat/share/insertShare", "/S62070005"]
, ["/weChat/share/queryMyShareList", "/Q62070007"]
, ["/weChat/favorite/insertFavorite", "/S62070006"]
, ["/weChat/favorite/canalFavorite", "/S62070007"]
, ["/weChat/favorite/queryMyFavorite", "/Q62070008"]
, ["/weChat/favorite/whetherFavorite", "/S62070008"]
// , ["/weChat/registration/insertRegistration", "/Q62070009"]
, ["/weChat/share/queryById", "/Q62070010"]
, ["/weChat/userRobot/queryChatMessagesPage", "/Q62070011"]
, ["/weChat/userRobot/getReply", "/Q62070012"]
, ["/weChat/userRobot/updateUsefulFlag", "/S62070009"]
, ["/user/weChat/queryByOpenId", "/Q62070013"]
, ["/user/weChat/updateWechatUserAccount", "/S62070010"]
, ["/weChat/login/phone", "/Q62070014"]
, ["/weChat/login/auto", "/S62070011"]
, ["/weChat/queryByOpenId", "/Q62070015"]
, ["/weChat/message/queryNewestMessage", "/S62070012"]
, ["/weChat/hotSearch/queryLimit6", "/Q62070016"]
, ["/weChat/search/queryBySearchName", "/Q62070017"]
, ["/weChat/search/queryTitles", "/Q62070018"]
, ["/weChat/production/queryKeyProduction", "/Q62070019"]
, ["/weChat/pollingPicture/queryAll", "/Q62070020"]
, ["/weChat/solution/queryHomeDisplaySolution", "/Q62070021"]
, ["/weChat/solution/queryHomeDisplaySolutionTypeName", "/Q62070022"]
, ["/weChat/registration/insertRegistration", "/S62070013"]
, ["/weChat/feedback/insertFeedback", "/S62070014"]
, ["/weChat/getAppletQRCode", "/Q62070023"]
, ["/weChat/share/shareByPicture", "/S62070015"]
, ["/weChat/message/addMessageToCurrentMessage", "/S62070016"]
, ["/picture/compositePicture", "/S62070017"]
, ["/verificationCode/login/sendVerifyCode", "/S62070018"]
, ["/weChat/deleteAccount", "/S62070019"]
, ["/picture/download", "/S62070020"]
, ["/picture/downloadVideo", "/S62070021"]
, ["/picture/downloadBkPic", "S62070022"]
, ["/wechat/picture/getPic", "/Q62070024"]
, ["/weChat/information/queryInfoByPage", "/Q62070025"]
, ["/weChat/information/queryInfo3", "/Q62070026"]
, ["/weChat/information/queryDetailById", "/Q62070027"]
, ["/weChat/querySendInfo", "/Q62070028"]
])

function downloadBkPic(val) {
	let url=`${baseURL}/${mappingAdress.get("/picture/downloadBkPic")}?picName=${val}&scale=1`
	return url
}
function download(val) {
	let url=`${baseURL}/${mappingAdress.get("/picture/download")}?fileId=${val}&scale=1`
	return url
}

function downloadVideo(val) {
	let url=`${baseURL}/${mappingAdress.get("/picture/downloadVideo")}?fileId=${val}&scale=1&fileName=a.mp4`
	console.log('url: ', url);
	return url
}

export const downloadAppletRichPic = (val)=> {
	let url=`${baseURL}/${mappingAdress.get("/wechat/picture/getPic")}?picName=${val}&scale=1`
	return url
}

function isEmpty(value) {
	if (value === null || value === undefined || value === '') {
		return true;
	} else {
		return false;
	}
}

function formatMoney(value, style = '') {
	if (value === null || value === undefined || value === 0 || value === '') {
		return '0.00';
	}
	let numType = '' //正 /负数
	if (value < 0) {
		value = Math.abs(value)
		numType = '-'
	}
	if (style === 'number') {
		return parseFloat(value.replace(/[^\d\.-]/g, ""));
	} else {
		let n = 2;
		value = parseFloat((value + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
		let l = value.split(".")[0].split("").reverse();
		let r = value.split(".")[1];
		let t = "";
		for (let i = 0; i < l.length; i++) {
			t += l[i] + ((i + 1) % 3 === 0 && i + 1 !== l.length ? "," : "");
		}
		return (numType + t.split("").reverse().join("") + "." + r);
	}
}

function formatMoneyAbs(value, style = '') {
	if (value === null || value === undefined || value === 0 || value === '') {
		return '0.00';
	}
	if (value < 0) {
		value = Math.abs(value)
	}
	if (style === 'number') {
		return parseFloat(value.replace(/[^\d\.-]/g, ""));
	} else {
		let n = 2;
		value = parseFloat((value + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
		let l = value.split(".")[0].split("").reverse();
		let r = value.split(".")[1];
		let t = "";
		for (let i = 0; i < l.length; i++) {
			t += l[i] + ((i + 1) % 3 === 0 && i + 1 !== l.length ? "," : "");
		}
		return (t.split("").reverse().join("") + "." + r);
	}
}

const baseApi = {
	// 预演
	// trial: 'https://yqy.test.dev.psbc.com:30085/stage-api/saas/finance',
	// 定版
	// trial: 'https://yqy.dev.psbc.com:30085/stage-api/saas/finance',
	// 生產
	// release: 'https://yqy.psbc.com/prod-api/saas/finance'

	develop: 'https://yqy.psbc.com/prod-api/saas/finance',
	trial: 'https://yqy.psbc.com/prod-api/saas/finance',
	release: 'https://yqy.psbc.com/prod-api/saas/finance'
}

const getBaseH5Url = (env,phone) => {
	switch (env) {
		case 'develop':
			return `https://cbcbp.dev.psbc.com:8443/t2/xwyloan/#/home?promoChannel=77&enterModel=01&phone=${phone}`
		case 'trial':
			return `https://cbcbp.dev.psbc.com:8443/t2/xwyloan/#/home?promoChannel=77&enterModel=01&phone=${phone}`
		case 'release':
				return `https://precredit.psbc.com/cbcbp/xwyloan/#/home?promoChannel=77&enterModel=01&phone=${phone}`
		default:
			return `https://cbcbp.dev.psbc.com:8443/t2/xwyloan/#/home?promoChannel=77&enterModel=01&phone=${phone}`
	}
}

// let baseURL = 'https://www.xzminiweb.cn/api/finance' 
// let baseURL = 'https://wap.gslztl.psbc.com/api/finance'
// let baseURL = 'https://admin.yqy.dev.psbc.asia:30085/stage-api/saas/finance'
// let baseURL = 'https://120.209.164.251:30085/stage-api/saas/finance'
export const envVersion =  wx.getAccountInfoSync().miniProgram.envVersion
export const getH5Url = (phone) => getBaseH5Url(envVersion,phone)
console.log('envVersion: ', envVersion);
let baseURL = baseApi[envVersion]
// let baseURL = 'https://wap.shenzhen.psbc.com/api/finance'
// if (process.env.NODE_ENV === 'development') {
	//  baseURL = 'http://183.162.246.178:8848/api/rent'
// } else {
// 	baseURL = 'http://183.162.246.178:8848/api/rent'
// }

function getPhone(val) {
	let phone = '';
	if (isEmpty(val)) {
		phone = "暂无";
	} else {
		phone = val;
	}
	return phone;
}

function getDate(val) {
	if (isEmpty(val)) {
		return '';
	}
	let str = val.substr(0, 10);
	return str;
}

function getDiffDate(start, end) {
	let startDays = new Date(start).getTime() / 86400000;
	let endDays = new Date(end).getTime() / 86400000;
	let day = Math.floor(endDays - startDays);
	if (day > 0) {
		return day;
	} else {
		return 0;
	}
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : `0${n}`
}

const formatTime = (date, format) => {
	const formatArr = ['YYYY', 'MM', 'DD', 'hh', 'mm', 'ss']
	const returnArr = []
	returnArr.push(date.getFullYear())
	returnArr.push(formatNumber(date.getMonth() + 1))
	returnArr.push(formatNumber(date.getDate()))
	returnArr.push(formatNumber(date.getHours()))
	returnArr.push(formatNumber(date.getMinutes()))
	returnArr.push(formatNumber(date.getSeconds()))

	for (const i in returnArr) {
		format = format.replace(formatArr[i], returnArr[i])
	}
	return format
}

const getDiffTime = recordTime => {
	if (recordTime != '') {
		recordTime = new Date(recordTime)
		const minute = 1000 * 60
		const hour = minute * 60
		const day = hour * 24
		const now = new Date()
		const diff = now - recordTime
		let result = ''
		if (diff < 0) {
			return result
		}
		const weekR = diff / (7 * day)
		const dayC = diff / day
		const hourC = diff / hour
		const minC = diff / minute

		const yesterday = new Date(now - 1000 * 60 * 60 * 24)
		let returnTime = ''

		if (
			yesterday.getYear() === recordTime.getYear() &&
			yesterday.getMonth() === recordTime.getMonth() &&
			yesterday.getDate() === recordTime.getDate()
		) {
			returnTime = `昨天 ${formatTime(recordTime, 'hh:mm')}`
		} else if (dayC > 1) {
			returnTime = formatTime(recordTime, 'YYYY/MM/DD hh:mm')
		} else {
			returnTime = formatTime(recordTime, 'hh:mm')
		}

		if (weekR >= 1) {
			result = `${formatTime(recordTime, 'YYYY/MM/DD hh:mm')}`
		} else if (dayC == 1 || (hourC < 24 && recordTime.getDate() != now.getDate())) {
			result = `昨天 ${formatTime(recordTime, 'hh:mm')}`
		} else if (dayC > 1) {
			result = `${formatTime(recordTime, 'YYYY/MM/DD hh:mm')}`
		} else if (hourC >= 1) {
			result = `今天 ${formatTime(recordTime, 'hh:mm')}`
		} else if (minC >= 1) {
			result = `${parseInt(minC)}分钟前`
		} else {
			result = '刚刚'
		}
		returnTime = result
		return returnTime
	} else {
		return ''
	}
}


/*输入框防抖*/
const antiShake = function(fn, delay) {
	let timer = null;
	return function() {
		let content = this;
		let args = arguments;
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			fn.apply(content, args);
		}, delay);
	};
};

/*按钮节流*/
/*
import throttle from "@/utils/throttle"
methods:{
    submit:throttle(function()  {
		console.log('节流')
    },500)
}
*/

const throttle = (func, delay) => {
	// 缓存一个定时器
	let timer = null;
	// 这里返回的函数是每次用户实际调用的节流函数
	return function(...args) {
		if (!timer) {
			//判断timer是否有值,如果没有则说明定时器不存在即可继续执行
			timer = setTimeout(() => {
				//关
				func.apply(this, arguments);
				timer = null; //开
			}, delay);
		}
	};
};



export {
	formatMoney as formatMoney,
	formatMoneyAbs as formatMoneyAbs,
	isEmpty as isEmpty,
	getPhone as getPhone,
	getDate,
	baseURL,
	getDiffTime,
	getDiffDate,
	antiShake,
	throttle,
	mappingAdress,
	download,
	downloadVideo,
	downloadBkPic
}